package ee.project;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.TreeSet;
import java.util.Vector;

public class CollectionsTest {

	private static final int NUM_ITEMS = 100000;

	private Random rand;

	public CollectionsTest() {
		rand = new Random();
	}

	public static void main(String[] args) throws InterruptedException {
		
		CollectionsTest ct = new CollectionsTest();
		Collection<Integer> arrayList = new ArrayList<Integer>();
		// Collection<Integer> arrayList = Collections
		// .synchronizedList(new ArrayList<Integer>());
		ct.test(arrayList);
		Collection<Integer> linkedList = new LinkedList<Integer>();
		// Collection<Integer> linkedList = Collections
		// .synchronizedList(new LinkedList<Integer>());
		ct.test(linkedList);
		Collection<Integer> vector = new Vector<Integer>();
		// Collection<Integer> vector = Collections
		// .synchronizedList(new Vector<Integer>());
		ct.test(vector);
		Collection<Integer> treeSet = new TreeSet<Integer>();
		// Collection<Integer> treeSet = Collections
		// .synchronizedSet(new TreeSet<Integer>());
		ct.test(treeSet);
		Collection<Integer> hashSet = new HashSet<Integer>();
		// Collection<Integer> hashSet = Collections
		// .synchronizedSet(new HashSet<Integer>());
		ct.test(hashSet);
	}

	private void test(Collection<Integer> c) throws InterruptedException {
		System.out.println("Testing " + c.getClass());
		Stopwatch timer = new Stopwatch().start();
		add(c);
		timer.stop();
		System.out.println("Add. Elapsed time: " + timer.getTimeElapsed()
				+ " ms");
		timer.reset().start();
		iterate(c);
		timer.stop();
		System.out.println("Iterate. Elapsed time: " + timer.getTimeElapsed()
				+ " ms");
		if (c instanceof List<?>) {
			List<Integer> l = (List<Integer>) c;
			timer.reset().start();
			randomAccess(l);
			timer.stop();
			System.out.println("Random access. Elapsed time: "
					+ timer.getTimeElapsed() + " ms");
		}
		timer.reset().start();
		remove(c);
		timer.stop();
		System.out.println("Remove. Elapsed time: " + timer.getTimeElapsed()
				+ " ms");
		System.out.println();
	}

	public void add(Collection<Integer> c) {
		for (int i = 0; i < NUM_ITEMS; i++) {
			c.add(i);
		}
	}

	public void iterate(Collection<Integer> c) {
		for (int i = 0; i < 100; i++) {
			Iterator<Integer> iter = c.iterator();
			while (iter.hasNext()) {
				Object o = iter.next();
			}
		}
	}

	public void remove(Collection<Integer> c) {
		Iterator<Integer> iter = c.iterator();
		while (iter.hasNext()) {
			Object o = iter.next();
			iter.remove();
		}
	}

	public void randomAccess(List c) {
		for (int i = 0; i < 1000; i++) {
			Object o = c.get(random());
		}
	}

	private int random() {
		return rand.nextInt(NUM_ITEMS);
	}
}